package com.qian.service.ddj.util.YLutil.YLUtils;

import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

/**
 * api工具类
 * @author chenzf
 * @date 2018年1月23日
 */
public class ApiUtils {
	public static final String MD5_ALGORITHM_NAME = "MD5";
	private static final char[] HEX_CHARS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e',
			'f' };
	public static final String DEFAULT_ENCODING = "UTF-8";

	/**
	 * 标记OutSign的字段不参与签名
	 * @param object
	 * @param apiKey
	 * @return
	 */

	public static String getSign(Object object, String apiKey) {
		Gson gson = JsonUtils.build(true, "yyyy-MM-dd HH:mm:ss", new ExclusionStrategy() {

			@Override
			public boolean shouldSkipField(FieldAttributes f) {
				if (f.getAnnotation(OutSign.class) != null) {
					return true;
				}
				return false;
			}

			@Override
			public boolean shouldSkipClass(Class<?> clazz) {
				return false;
			}
		}).create();

		String getSignJson = gson.toJson(object);
		if (StringUtils.isBlank(getSignJson)) {
			return null;
		}
		Gson createGson = JsonUtils.createGson();
		Map<String, String> jsonMap = createGson.fromJson(getSignJson, new TypeToken<TreeMap<String, String>>() {
		}.getType());
		StringBuilder builder = new StringBuilder();
		buildRequestBody(jsonMap, builder);
		builder.append("&key=").append(apiKey);
		System.out.println("加密的数据："+builder.toString());
		return md5Encrypt(builder.toString()).toUpperCase();
	}

	public static String md5Encrypt(String input) {
		try {
			byte[] digest = MessageDigest.getInstance(MD5_ALGORITHM_NAME).digest(input.getBytes(DEFAULT_ENCODING));
			return new String(encodeHex(digest));
		} catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
			System.err.println( ex);
		}
		return null;
	}

	private static char[] encodeHex(byte[] bytes) {
		char chars[] = new char[32];
		for (int i = 0; i < chars.length; i = i + 2) {
			byte b = bytes[i / 2];
			chars[i] = HEX_CHARS[(b >>> 0x4) & 0xf];
			chars[i + 1] = HEX_CHARS[b & 0xf];
		}
		return chars;
	}

	/**
	 * 拼接key和value 
	 */
	private static void appendKeyValue(StringBuilder builder, Iterator<Entry<String, String>> jsonIt) {
		Entry<String, String> next = jsonIt.next();
		builder.append(next.getKey()).append("=").append(next.getValue());
	}

	/**
	 * 构建请求数据 例：1=1&2=2
	 * @param param 请求参数
	 * @param builder  构建字段
	 * @return
	 */
	public static String buildRequestBody(Map<String, String> param, StringBuilder builder) {
		Iterator<Entry<String, String>> iterator = param.entrySet().iterator();
		appendKeyValue(builder, iterator);
		while (iterator.hasNext()) {
			builder.append("&");
			appendKeyValue(builder, iterator);
		}
		return builder.toString();
	}
}
